package com.example.jones.test;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.constant.AppConstant;
import com.example.constant.VariableKey;
import com.example.jones.function.RegisterView;
import com.example.jones.function.LoginView.BaseUiListener;
import com.example.util.HttpUtil;
import com.example.util.HttpUtilWithParameter;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class UserLogin extends Activity {
    private TextView username1, password1;
    private TextView usernamereg, regpwd,regpwd_repeat;
    private Button login, qq_account;
    private Button register_start = null;
    private Button register = null;
    private RegisterView registerView = null;
    private LinearLayout loginlayout = null;
    
 // qq登录
    public Tencent mTencent;
    public String APP_ID = "101041342";
    public String SCOPE = "get_user_info,get_simple_userinfo,add_share,add_topic";
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initView();
		mTencent = Tencent.createInstance(APP_ID, this);
	}

	private void initView(){
		username1 = (TextView) findViewById(R.id.username1);
		password1 = (TextView) findViewById(R.id.password1);
		
		
        login = (Button) findViewById(R.id.login);
        register_start = (Button) findViewById(R.id.register_start);
        qq_account = (Button) findViewById(R.id.qq_account);
        loginlayout = (LinearLayout) findViewById(R.id.login_layout);
        
        //注册
        
        
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = HttpUtil.Base_url + "/LoginService";
                try {
                    if (username1.getText().toString().equals("")
                            || password1.getText().toString().equals("")) {
                        Toast.makeText(UserLogin.this, "请填写用户ID和密码！", 1000).show();
                        return;
                    } else {
                        if (HttpUtilWithParameter.ValidUser(url, username1
                                .getText().toString(), password1.getText()
                                .toString())) {
                            Toast.makeText(UserLogin.this, "登录成功！", 1000).show();
                            Intent it = new Intent(UserLogin.this, MainActivity.class);
            				
                            UserLogin.this.startActivity(it);
//                            UserLogin.this.finish();
                        } else {
                            Toast.makeText(UserLogin.this, "用户ID或密码错误！", 1000).show();
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        
        this.register_start.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				setContentView(R.layout.register);
				register = (Button) findViewById(R.id.register);
				usernamereg = (TextView) findViewById(R.id.usernamereg);
				regpwd = (TextView) findViewById(R.id.regpwd);
				regpwd_repeat = (TextView) findViewById(R.id.regpwd_repeat);
				register.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						registerClick();
		            }
				});
			}
		});
        
        this.qq_account.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				qqcountLoginClick();
			}
		});
        
	}
	
	private void registerClick(){		
		
		
        String url = HttpUtil.Base_url + "/RegisterService";
        try {
            if (usernamereg.getText().toString().equals("")
                    || regpwd.getText().toString().equals("")) {
                Toast.makeText(UserLogin.this, "请填写用户ID和密码！", 1000).show();
                return;
            }else if(!regpwd.getText().toString().equals(regpwd_repeat.getText().toString())){
            	Toast.makeText(UserLogin.this, "两次输入的密码不对", 1000).show();
            }else {
                if (HttpUtilWithParameter.ValidUser(url, usernamereg
                        .getText().toString(), regpwd.getText()
                        .toString())) {
                    Toast.makeText(UserLogin.this, "注册成功", 1000).show();
                    Intent it = new Intent(UserLogin.this, MainActivity.class);
    				
//                    UserLogin.this.startActivity(it);
                    UserLogin.this.finish();
                } else {
                    Toast.makeText(UserLogin.this, "注册用户时出错！", 1000).show();
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * QQ账号登录
	 */
	private void qqcountLoginClick(){
		if ((null !=this.mTencent)&&(!this.mTencent.isSessionValid())) {
			IUiListener listener = new BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					Toast.makeText(UserLogin.this, "登录成功，即将进入主页",
							Toast.LENGTH_SHORT).show();
					
					try {
						final String userID = values.getString("openid");
						final String thirdAccountID = values.getString("access_token");
						final String type = "Q";
						
						AppConstant.GLOBAL_VARIABLE.put(VariableKey.USER_ID, userID);
						
						new Thread(new Runnable() {
							
							@Override
							public void run() {
								HttpPost post = new HttpPost(HttpUtil.Base_url + "/AddThirdAccountService");
								String thacct = "{\"userID\":\""+userID+"\",\"thirdAccountID\":\""+thirdAccountID+"\",\"type\":\""+type+"\"}";
					            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
					            NameValuePair pair1 = new BasicNameValuePair("thacct", thacct);
					            pairs.add(pair1);
					            HttpEntity entity;
								try {
									entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);// 设置编码，防止中文乱码
									post.setEntity(entity);
									HttpResponse httpResponse = new DefaultHttpClient().execute(post);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						});
					} catch (JSONException e) {
						e.printStackTrace();
					}
					Intent it = new Intent(UserLogin.this, MainActivity.class);
					UserLogin.this.startActivity(it);
					UserLogin.this.finish();
				}
			};
			
			this.mTencent.login(UserLogin.this, SCOPE, listener);
		}else {
			Intent it = new Intent(UserLogin.this, MainActivity.class);
			UserLogin.this.startActivity(it);
			UserLogin.this.finish();
		}
	}
	public class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {
        }

        @Override
        public void onError(UiError e) {
            Toast.makeText(UserLogin.this, e.toString(), Toast.LENGTH_SHORT).show(); 
        }

        @Override
        public void onCancel() {
        }
    }
	
	 
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        mTencent.onActivityResult(requestCode, resultCode, data);
	    }
}
